﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace LCS.WPF.Views
{
    public class RelayCommand : ICommand

    {

        #region 字段

        readonly Func<bool> _canExecute;

        readonly Action _execute;

        #endregion



        #region 构造函数

        public RelayCommand(Action execute)

            : this(execute, null)

        {

        }

        public RelayCommand(Action execute, Func<bool> canExecute)

        {

            if (execute == null)

                throw new ArgumentNullException("execute");

            _execute = execute;

            _canExecute = canExecute;

        }

        #endregion



        #region ICommand的成员

        public event EventHandler CanExecuteChanged

        {

            add

            {
                if (_canExecute != null)

                    CommandManager.RequerySuggested += value;

            }

            remove

            {

                if (_canExecute != null)

                    CommandManager.RequerySuggested -= value;

            }

        }




        public bool CanExecute(object parameter)

        {

            return _canExecute == null ? true : _canExecute();

        }



        public void Execute(object parameter)

        {

            _execute();

        }


        #endregion

        /// <summary>
        /// 主动引发CanExecute函数重新执行来更新界面元素的绑定显示状态
        /// </summary>
        public void RaiseCanExecuteChanged()
        {
            CommandManager.InvalidateRequerySuggested();
        }
    }
}
